package com.baidu.ueditor.upload;

import com.baidu.ueditor.ConfigManager;
import com.baidu.ueditor.ConfigPropManager;
import com.baidu.ueditor.PathFormat;
import com.baidu.ueditor.define.AppInfo;
import com.baidu.ueditor.define.BaseState;
import com.baidu.ueditor.define.FileType;
import com.baidu.ueditor.define.State;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class BinaryUploader {

	public static final State save(HttpServletRequest request, Map<String, Object> conf) {
		MultipartFile multipartFile = null;

		boolean isAjaxUpload = request.getHeader("X_Requested_With") != null;

		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
		//检查form中是否有enctype="multipart/form-data"
		if(!multipartResolver.isMultipart(request)){
			return new BaseState(false, AppInfo.NOT_MULTIPART_CONTENT);
		}

		ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());

		if (isAjaxUpload) {
			upload.setHeaderEncoding("UTF-8");
		}
		try{
			//将request变成多部分request
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
			//获取multiRequest 中所有的文件名
			Iterator<String> iterator = multiRequest.getFileNames();
			//遍历文件
			while(iterator.hasNext()) {
				multipartFile = multiRequest.getFile(iterator.next().toString());
				if(multipartFile!=null)
					break;
			}

			if (multipartFile == null) {
				return new BaseState(false, AppInfo.NOTFOUND_UPLOAD_DATA);
			}

			String savePath = (String) conf.get("savePath");
			String originFileName = multipartFile.getOriginalFilename();
			String suffix = FileType.getSuffixByFilename(originFileName);
			originFileName = originFileName.substring(0, originFileName.length() - suffix.length());
			savePath = savePath + suffix;

			long maxSize = ((Long) conf.get("maxSize")).longValue();

			if (!validType(suffix, (String[]) conf.get("allowFiles"))) {
				return new BaseState(false, AppInfo.NOT_ALLOW_FILE_TYPE);
			}

			savePath = PathFormat.parse(savePath, originFileName);

			//modified by Ternence
			String rootPath = ConfigPropManager.getString("config.upload.path");

			if(null==rootPath || rootPath.equals("")){
				rootPath = ConfigManager.getRootPath(request,conf);
			}
			String physicalPath = rootPath + savePath;

			State storageState = StorageManager.saveFileByInputStream(multipartFile.getInputStream(), physicalPath, maxSize);

			if (storageState.isSuccess()) {
				storageState.putInfo("url", PathFormat.format(savePath));
				storageState.putInfo("type", suffix);
				storageState.putInfo("original", originFileName + suffix);
			}
			return storageState;
		} catch (IOException e) {

		}
		return new BaseState(false, AppInfo.IO_ERROR);
	}

	private static boolean validType(String type, String[] allowTypes) {
		List<String> list = Arrays.asList(allowTypes);

		return list.contains(type);
	}
}
